

#include <phApp_Init.h>
#include "log/log2.h"


phStatus_t read_hid_iclass_card(uint8_t *uid, uint8_t *len)
{
	phStatus_t status;
	uint8_t *rx_buf;
	uint16_t rx_len;
 	void * hal = phNfcLib_GetDataParams(PH_COMP_HAL);

	LOG2_DBG("start hid iclass card search..");
	for(int i=0;i<3;i++)
	{
		/* Off the Rf field */
		PH_CHECK_SUCCESS_FCT(status, phhalHw_FieldOff(hal));
		phOsal_ThreadDelay(2);
		
		/* Apply Protocol Setting for Selected Tech  */
		PH_CHECK_SUCCESS_FCT(status, phhalHw_ApplyProtocolSettings(hal,
			(uint8_t)(PHHAL_HW_CARDTYPE_ISO15693 & 0xFFU)));
		
		PH_CHECK_SUCCESS_FCT(status, phhalHw_FieldOn(hal));
		PH_CHECK_SUCCESS_FCT(status, phhalHw_SetConfig(hal, PHHAL_HW_CONFIG_POLL_GUARD_TIME_US,
			PHAC_DISCLOOP_CONFIG_GTV_VALUE_US));
		PH_CHECK_SUCCESS_FCT(status, phhalHw_SetConfig(hal, PHHAL_HW_CONFIG_TIMEOUT_VALUE_US,
			500U));
		PH_CHECK_SUCCESS_FCT(status, phhalHw_SetConfig(hal, PHHAL_HW_CONFIG_RXCRC, PH_OFF));
		PH_CHECK_SUCCESS_FCT(status, phhalHw_SetConfig(hal, PHHAL_HW_CONFIG_TXCRC, PH_OFF));
		

		phOsal_ThreadDelay(5);
		
		phhalHw_Exchange(hal, PH_EXCHANGE_DEFAULT, (uint8_t []){0x0A}, 1, &rx_buf, &rx_len);
		
		phOsal_ThreadDelay(3);
		
		if((status = phhalHw_Exchange(hal, PH_EXCHANGE_DEFAULT, (uint8_t []){0x0C}, 1, &rx_buf, &rx_len) & PH_COMPID_MASK) == PH_ERR_SUCCESS)
		{
			uint8_t buf[16] = {0x81};
			memcpy(buf + 1, rx_buf, sizeof(buf)< rx_len ? sizeof(buf) : rx_len);
			status = phhalHw_Exchange(hal, PH_EXCHANGE_DEFAULT, buf, 9, &rx_buf, &rx_len) & PH_COMPID_MASK;
			
			/* Check if we have a card in the RF field.
			 * If so, check what card it is. */
			if (PH_ERR_SUCCESS == status)
			{
				*len = 0x08;
				memcpy(uid, rx_buf, *len);
				LOG2_DBG("card uid: %02x%02x%02x%02x%02x%02x%02x%02x", uid[0], uid[1], uid[2], uid[3], uid[4], uid[5], uid[6], uid[7]);
				return status;
			}
			else
			{
				LOG2_ERR("phhalHw_Exchange request 0x81 return error code: %04X", status);
			}
		}
	}
	
	return status;
}


